<style lang="scss" scoped>
@import "@/styles/mixins.scss";
.xjw-checkbox {
  height: 72upx;
  text-align: center;
  background: #f4f4f4;
  border-radius: 4upx;
  font-size: 26upx;
  text-align: center;
  line-height: 68upx;
  box-sizing: border-box;
  border: 2upx solid transparent;
  @include text-overflow;
  color: $f606266;

  &.is-disabled {
    background: #999;
    color: #666;
    border-color: transparent !important;
  }
  &--check {
    background: $thin-base-color;
    border-color: $base-color;
    color: $base-color;
  }
}
</style>
<template>
  <view
    @tap.stop="click"
    class="xjw-checkbox"
    :style="[itemStyle]"
    :class="{ 'xjw-checkbox--check': isCheck, 'is-disabled': disabled }"
  >
    <slot></slot>
  </view>
</template>

<script lang="ts">
import Vue from "vue";
import { Component, Prop, Inject, Watch } from "vue-property-decorator";
import { isObject, isArray } from "../lib/function/index";

@Component({
  name: "checkbox",
})
export default class Index extends Vue {
  @Prop({ type: [Number, String, Object] }) checkValue;
  @Prop({ type: String }) keyValue;
  @Prop({ type: Boolean, default: false }) disabled;

  @Inject()
  group;

  isCheck: boolean = false;

  get itemStyle() {
    return this.group.style;
  }

  @Watch("group.value", {
    immediate: true,
    deep: true,
  })
  WatchGroupValue(newValue, ordValue) {
    if (isArray(newValue)) {
      if (this.keyValue) {
        if (!isObject(this.checkValue)) {
          // eslint-disable-next-line no-console
          console.error(
            `传入了keyValue即为对象模式,但是传入的是${
              Array.isArray(this.checkValue) ? "数组" : typeof this.checkValue
            } `
          );
        } else {
          this.isCheckValue(newValue, this.keyValue);
        }
      } else {
        this.isCheckValue(newValue);
      }
    }
  }

  isCheckValue(list: Array<any>, key?: string) {
    if (
      list.some((v) => {
        return key ? v[key] === this.checkValue[key] : v === this.checkValue;
      })
    ) {
      this.isCheck = true;
    } else {
      this.isCheck = false;
    }
  }

  _result() {
    return this.checkValue;
  }

  click() {
    if (!this.disabled) {
      this.isCheck = !this.isCheck;
      this.group.$emit("childCheckChange", this.checkValue);
    }
  }
}
</script>
